package test;


import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache extends LinkedHashMap<String, Integer> {
    public int capacity;

    public LRUCache(int capacity) {
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    @Override
    public Integer get(Object key) {
        return super.getOrDefault(key, -1);
    }

    @Override
    public Integer put(String key, Integer value) {
        return super.put(key, value);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
        return size() > capacity;
    }

    public static void main(String[] args) {
        LRUCache lruCache = new LRUCache(3);
        lruCache.put("a", 1);
        lruCache.put("b", 2);
        lruCache.put("c", 3);
        System.out.println(lruCache);
        System.out.println("获取元素");
        System.out.println(lruCache.get("b"));
        System.out.println(lruCache);
        System.out.println(lruCache.get("a"));
        System.out.println(lruCache);
        System.out.println("存放元素,会删除头结点，因为头结点是最近最少使用的");
        lruCache.put("d", 4);
        System.out.println(lruCache);
    }

    public static void main2(String[] args) {
        LinkedHashMap<String, Integer> linkedHashMap =
                new LinkedHashMap<String, Integer>(16, 0.7f, true);
        linkedHashMap.put("a", 1);
        linkedHashMap.put("b", 2);
        linkedHashMap.put("c", 3);
        System.out.println(linkedHashMap);
        System.out.println("获取元素");
        System.out.println(linkedHashMap.get("a"));
        System.out.println(linkedHashMap);
        System.out.println(linkedHashMap.get("b"));
        System.out.println(linkedHashMap);
        System.out.println(linkedHashMap.get("c"));
        System.out.println(linkedHashMap);//把常用的数据放到了尾巴 不常用的放在头部便于删除
    }

    public static void main1(String[] args) {
        LinkedHashMap<String, Integer> linkedHashMap =
                new LinkedHashMap<String, Integer>(16, 0.7f, false);
        linkedHashMap.put("a", 1);
        linkedHashMap.put("b", 2);
        linkedHashMap.put("c", 3);
        System.out.println(linkedHashMap);
        System.out.println("获取元素");
        System.out.println(linkedHashMap.get("a"));
        System.out.println(linkedHashMap);
    }
}
